//
//  DateUntils.m
//  DailyRecord
//
//  Created by Gin on 2022/4/6.
//

#import "DateUntils.h"

static NSDateFormatter * formatter;

@implementation DateUntils

+ (void)initialize{
    formatter = [[NSDateFormatter alloc] init];
}

+ (NSDate*)getPriousorLaterDateFromDate:(NSDate*)date withMonth:(int)month{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:month];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];// NSGregorianCalendar
    NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
    return mDate;
}

+ (NSArray<NSString *> *)generateDateStringTypeYYYYMMPrevious:(int)month{
    NSMutableArray *dateStrings = [NSMutableArray array];
    for (int i = 0 ; i < month; i++) {
        NSDate *previousDate = [self getPriousorLaterDateFromDate:[NSDate date] withMonth:-i];
        [formatter setDateFormat:kYYYYMM];
        NSString * str = [formatter stringFromDate:previousDate];
        [dateStrings addObject:str];
    }
    return dateStrings;
}

+ (NSArray<NSString *> *)getAllDaysWithMonth{
    NSUInteger dayCount = [self getInMonthNumberOfDays]; //一个月的总天数
    NSDate * currentDate = [NSDate date];
    [formatter setDateFormat:kYYYYMM];
    NSString * str = [formatter stringFromDate:currentDate];
    [formatter setDateFormat:kYYYYMMDD];
    NSMutableArray *dateTimeArray = [NSMutableArray array];
    for (NSInteger i = 1; i <= dayCount; i++) {
        NSString * sr = [NSString stringWithFormat:@"%@-%ld",str,i];
        [dateTimeArray addObject:sr];
    }
    return dateTimeArray;
}

+ (NSInteger)getInMonthNumberOfDays{
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate * currentDate = [NSDate date];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay
                                   inUnit: NSCalendarUnitMonth
                                  forDate:currentDate];
    return range.length;
}

+ (NSString *)getCurrentYearMonth{
    NSDate * currentDate = [NSDate date];
    [formatter setDateFormat:kYYYYMM];
    NSString * str = [formatter stringFromDate:currentDate];
    return str;
}

+ (NSString *)formatDate:(NSDate *)date withType:(NSString *)type{
    [formatter setDateFormat:type];
    NSString * str = [formatter stringFromDate:date];
    return str;
}

+ (NSDate *)formatString:(NSString *)string withType:(NSString *)type{
    [formatter setDateFormat:type];
    NSDate *date = [formatter dateFromString:string];
    return date;
}

@end
